package v1

import (
	"gitee.com/CrazyMage/blog-service/global"
	"gitee.com/CrazyMage/blog-service/internal/service"
	"gitee.com/CrazyMage/blog-service/pkg/app"
	"gitee.com/CrazyMage/blog-service/pkg/errcode"
	"github.com/gin-gonic/gin"
	"log"
)

type User struct{}

func NewUser() User {
	return User{}
}

func (t User) Login(c *gin.Context) {
	param := service.LoginReq{}
	response := app.NewResponse(c)
	valid, errs := app.BindAndValid(c, &param)
	if !valid {
		global.Logger.Errorf(c, "app.BindAndValid errs: %v", errs)
		response.ToErrorResponse(errcode.InvalidParams.WithDetails(errs.Errors()...))
		return
	}

	svc := service.New(c.Request.Context())
	resp, err := svc.Login(&param)

	if err != nil {
		global.Logger.Errorf(c, "svc.Login err: %v", err)
		log.Println(err)
		response.ToErrorResponse(errcode.ErrorLoginFail)
		return
	}
	response.ToResponse(resp)
	return
}

func (t User) Register(c *gin.Context) {
	param := service.RegisterReq{}
	response := app.NewResponse(c)
	valid, errs := app.BindAndValid(c, &param)
	if !valid {
		global.Logger.Errorf(c, "app.BindAndValid errs: %v", errs)
		response.ToErrorResponse(errcode.InvalidParams.WithDetails(errs.Errors()...))
		return
	}

	svc := service.New(c.Request.Context())
	resp, err := svc.Register(&param)

	if err != nil {
		global.Logger.Errorf(c, "svc.Register err: %v", err)
		response.ToErrorResponse(errcode.ErrorRegisterFail)
		return
	}
	response.ToResponse(resp)
	return
}

func (t User) Close(c *gin.Context) {
	param := service.CloseAccountReq{}
	response := app.NewResponse(c)
	valid, errs := app.BindUriAndValid(c, &param)
	if !valid {
		global.Logger.Errorf(c, "app.BindAndValid errs: %v", errs)
		response.ToErrorResponse(errcode.InvalidParams.WithDetails(errs.Errors()...))
		return
	}

	svc := service.New(c.Request.Context())
	resp, err := svc.CloseAccount(&param)

	if err != nil {
		global.Logger.Errorf(c, "svc.CloseAccount err: %v", err)
		response.ToErrorResponse(errcode.ErrorCloseAccountFail)
		return
	}
	response.ToResponse(resp)
	return
}
